package com.eascs.admin.o2o.enterpriseZX.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.o2o.enterpriseZX.entity.O2oEnterpriseZxEntity;
import com.eascs.admin.o2o.enterpriseZX.service.O2oEnterpriseZxService;
import com.eascs.admin.o2o.internal.util.BeanUtils;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.o2ozx.serviceimpl.O2oZxServiceImpl;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.crm.common.custnew.entity.CustomerEntity;
import com.eascs.crm.common.custnew.service.CustomerService;
import com.eascs.crm.common.service.ICustomerInfoService;
import com.eascs.datalist.entity.O2oDataListEntity;
import com.eascs.datalist.service.O2oDataListService;
import com.eascs.file.FileTypeConstants;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.OpenButton;
import com.eascs.site.view.button.ShowButtonFilter;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.web.url.UrlHelper;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.service.sys.SysOrgService;
import com.eascs.workflow.common.service.sys.SysPermissionService;

@RestController
@RequestMapping("/renterpriseZx")
public class O2oEnterpriseZxRestController extends BaseRestController {

	private static Logger logger = LoggerFactory.getLogger(O2oEnterpriseZxRestController.class);

	@Reference
	private SysPermissionService sysPermissionService;
	@Reference(retries = 3)
	private ICustomerInfoService iCustomerInfoService;
	
	@Autowired
	private O2oEnterpriseZxService o2oEnterpriseZxService;
	
	@Reference
	CustomerService customerService;
	
	@Reference
	SysOrgService sysOrgService;
	
	@Autowired
	private O2oDataListService o2oDataListService;
	
	@Autowired
	O2oZxServiceImpl o2oZxServiceImpl;
	
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	
	/**
	 * @Description:
	 * 				<p>
	 *               根据客户身份证查询是否可以进行企业征信查询
	 *               </p>
	 * @author yy
	 * @date 2017年7月14日 上午11:02:30
	 * @version V1.0
	 */
	@RequestMapping(value = "/checkLoan")
	public BaseRestResult<?> checkLoan(String idCard) {
		idCard = idCard.trim();
		//否存在客户系统（提示：系统查无此借款人）、改客户是否有新建、流程中的单据 
		CustomerEntity basic = customerService.queryCustomerEntityByIdCard(idCard);
		if(basic==null){
			return BaseRestResult.warn("is_no_user");
		}
		
		int count = o2oEnterpriseZxService.checkO2oQYzx(idCard.trim());
		if(count>0){
			return BaseRestResult.warn("is_has_qx");
		}
		
		return BaseRestResult.warn("success");

	}
	
	
	/**
	 * @Description:
	 * 				<p>
	 *               企业征信，企业征信信息
	 *               </p>
	 * @author yy
	 * @date 2017年10月16日 下午7:40:40
	 * @version V1.0
	 */
	@RequestMapping("/detail")
	public BaseRestResult<String> detailInfo(String id, String type,String idCard) {
		O2oEnterpriseZxEntity o2oEnterpriseZxEntity = new O2oEnterpriseZxEntity();
		if(StringUtil.isNotBlank(id)){
			o2oEnterpriseZxEntity = o2oEnterpriseZxService.getEntityById(id);
		}
		
		if(o2oEnterpriseZxEntity.getCustomerCard()==null){
			CustomerEntity basic = customerService.queryCustomerEntityByIdCard(idCard);
			if(basic!=null){
				o2oEnterpriseZxEntity.setCrmCustomerId(basic.getCustomerId());
				o2oEnterpriseZxEntity.setCustomerName(basic.getCustomerName());
				o2oEnterpriseZxEntity.setCustomerCard(basic.getIdNumber());
			}
		}
		String url = "enterpriseZx/detail";
		if (("VIEW").equals(type)) {
			url = "enterpriseZx/detail_view";// loanManagement/loan_gs_info
		}
		ViewContext.put("loanapplyNo", id);
		ViewContext.put("entity", o2oEnterpriseZxEntity);
		return new HtmlRestResult(url);
	}
	
	@RequestMapping(value = "/saveOrupdateo2oEnterpriseZxEntity")
	public BaseRestResult<?> saveOrupdateCustomerBasicInfo(O2oEnterpriseZxEntity entity) {
		
		if(StringUtil.isBlank(entity.getCrmCustomerId())){
			BaseRestResult.warn("请核对借款人身份证是否正确");
		}
		
		if(entity.getZxJyqxStart()==null){
			BaseRestResult.warn("营业期限开始时间不能为空");
		}
		
		if(entity.getZxJyqxEnd()==null){
			BaseRestResult.warn("营业期限结束时间不能为空");
		}
		
		if(entity.getOperatorId()==null){
			BaseRestResult.warn("请联想出信贷经理");
		}
		
		if(entity.getLtd()==null){
			BaseRestResult.warn("请联想出经办平台");
		}
		
		if(entity.getZxBank()==null){
			BaseRestResult.warn("请选择征信银行");
		}
		
		//一个自然月内在同一家银行仅能查询一次企业征信报告
		if(!StatusContexts.O2O_BANKTYPE_BC.equals(entity.getZxBank())){
			Boolean isMothSelected =o2oEnterpriseZxService.isMothSelectedQYZX(entity.getZxTyshxydm(), entity.getZxBank());
			if(isMothSelected){
				return BaseRestResult.warn("一个自然月内在同一家银行仅能查询一次企业征信报告");
			}
		}
		
		User user = UserHolder.getUser();
		ActOrgEntity actOrgEntity = null;
		actOrgEntity = sysOrgService.getOrgByUnitNo(entity.getLtd());
		if(actOrgEntity!=null){
			entity.setLtdName(actOrgEntity.getOrgName());
			entity.setLtdCode(actOrgEntity.getUnitCode());
		}
		if(entity.getId()==null){
			entity.setCreateDate(new Date());
			entity.setCreateId(user.getNo());
			entity.setCreateName(user.getCname());
			entity.setZxStatus(StatusContexts.O2O_NEW);
			entity.setIsDel(StatusContexts.O2O_NO);
			entity.setBillCode(o2oZxServiceImpl.buildCode("QYZX"));
			int count = o2oEnterpriseZxService.isnert(entity);
			if(count<0){
				logger.error("添加失败");
				BaseRestResult.warn("添加失败");
			}else{
				BaseRestResult.warn("添加成功");
			}
			return BaseRestResult.info("保存成功,请上传附件").andRedirect(UrlHelper.build("/enterpriseZx/findO2oEnterpriseZx?id=" + entity.getId()));
		}else{
			O2oEnterpriseZxEntity  entityj = o2oEnterpriseZxService.getEntityById(entity.getId());
			BeanUtils.copyProperties(entity,entityj );
			entityj.setModifyId(user.getNo());
			entityj.setModifyName(user.getCname());
			entityj.setModifyDate(new Date());
			int count = o2oEnterpriseZxService.update(entityj);
			if(count<0){
				logger.error("更新失败");
				BaseRestResult.warn("更新失败");
			}else{
				BaseRestResult.warn("更新成功");
			}
			return BaseRestResult.info("更新成功").andRedirect(UrlHelper.build("/enterpriseZx/list_detail?id="+entityj.getId()));
		}
		
	}
	
	
	/**
	 * 附件上传 局部刷新DIV
	 * 
	 * @param loanapplyNo
	 * @param massege
	 * @return
	 */
	@RequestMapping(value = "/uploadFile")
	public HtmlRestResult loanDetail(String id) {
       
		O2oEnterpriseZxEntity entity = o2oEnterpriseZxService.getEntityById(id);
		/**** 查询附件 ****/
		List<O2oDataListEntity> o2oDataList = o2oDataListService.findByEntityList(id);

		ViewContext.put("o2oDataList", o2oDataList);
		ViewContext.put("entity", entity);
		
		return new HtmlRestResult("enterpriseZx/uploadfileDiv");
	}
	
	
	/**
	 * 企业征信动态表单 附件上传 局部刷新DIV
	 * 
	 * @param id
	 * @param massege
	 * @return
	 */
	@RequestMapping(value = "/newQYZXzbzxqr")
	public HtmlRestResult newZXzbzxqr(String id) {

		O2oEnterpriseZxEntity o2oEnterprise = o2oEnterpriseZxService.getEntityById(id);
		/**** 查询附件 ****/
		List<O2oDataListEntity> o2oDataList = o2oDataListService.findByEntityList(id);

		List<O2oDataListEntity> dataList = o2oDataListService.findByEntityList(id);
		O2oDataListEntity ZXBGDATAEntity = null;
		for (int i = 0; i < dataList.size(); i++) {
			O2oDataListEntity entity = dataList.get(i);
			if (entity.getDatalistCode().equals(FileTypeConstants.ENTERPRISE_ZX_IDCARD)) {
				ZXBGDATAEntity = entity;
			}
		}
		ViewContext.put("ZXBGDATAEntity", ZXBGDATAEntity);
		ViewContext.put("o2oDataList", o2oDataList);
		ViewContext.put("o2oEnterprise", o2oEnterprise);
		return new HtmlRestResult("workflowcheck/newQYzx_zbzxqr_uploadDiv");
	}
	
	/**
	 * 企业征信动态表单 附件上传 局部刷新DIV
	 * 
	 * @param id
	 * @param massege
	 * @return
	 */
	@RequestMapping(value = "/newQYZXzbzxqr2")
	public HtmlRestResult newZXzbzxqr2(String id,String filetype) {

		O2oEnterpriseZxEntity o2oEnterprise = o2oEnterpriseZxService.getEntityById(id);
		/**** 查询附件 ****/
		List<O2oDataListEntity> o2oDataList = o2oDataListService.findByEntityList(id);

		List<O2oDataListEntity> dataList = o2oDataListService.findByEntityList(id);
		O2oDataListEntity ZXBGDATAEntity = null;
		for (int i = 0; i < dataList.size(); i++) {
			O2oDataListEntity entity = dataList.get(i);
			if (entity.getDatalistCode().equals(FileTypeConstants.ENTERPRISE_ZX_PFZXZZM)) {
				ZXBGDATAEntity = entity;
			}
		}
		ViewContext.put("ZXBGDATAEntity", ZXBGDATAEntity);
		ViewContext.put("o2oDataList", o2oDataList);
		ViewContext.put("o2oEnterprise", o2oEnterprise);
		return new HtmlRestResult("workflowcheck/newQYzx_zbzxqr_uploadDiv2");
	}
	
	/**
	 * 企业征信动态表单 附件上传 局部刷新DIV
	 * 
	 * @param id
	 * @param massege
	 * @return
	 */
	@RequestMapping(value = "/newQYZXzbzxqr5")
	public HtmlRestResult newZXzbzxqr5(String id,String filetype) {

		O2oEnterpriseZxEntity o2oEnterprise = o2oEnterpriseZxService.getEntityById(id);
		/**** 查询附件 ****/
		List<O2oDataListEntity> o2oDataList = o2oDataListService.findByEntityList(id);

		List<O2oDataListEntity> dataList = o2oDataListService.findByEntityList(id);
		O2oDataListEntity ZXBGDATAEntity = null;
		for (int i = 0; i < dataList.size(); i++) {
			O2oDataListEntity entity = dataList.get(i);
			if (entity.getDatalistCode().equals(FileTypeConstants.ENTERPRISE_ZX_PFZXSQS)) {
				ZXBGDATAEntity = entity;
			}
		}
		ViewContext.put("ZXBGDATAEntity", ZXBGDATAEntity);
		ViewContext.put("o2oDataList", o2oDataList);
		ViewContext.put("o2oEnterprise", o2oEnterprise);
		return new HtmlRestResult("workflowcheck/newQYzx_zbzxqr_uploadDiv5");
	}
	
	@RequestMapping(value = "/loanFqZxbgTD")
	public HtmlRestResult loanFqZxbgTD(String loanapplyNo, String IdNum) {
		PageResult<Object[]> pageResult = o2oEnterpriseZxService.loanFqZxbgnum(IdNum);
		String[] titles = { "征信单号","姓名", "营业执照名称", "企业征信报告日期", "征信创建时间","状态"};
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		SelectDataOption[] selectDataOptions = {null,null, null,null,null,new SelectDataOption("O2O_BILLSTATUS")};
		paginationInfo.setSelectDataOptions(selectDataOptions);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setBuildSelectBox(true);
		ViewContext.put("paginationInfo", paginationInfo);
		ViewContext.put("loanapplyNo", loanapplyNo);
		return HtmlRestResult.popHtmlFragment("enterpriseZx/loanFqZxbgTD");

	}
	
	@RequestMapping("/zxConfirmTD")
	public BaseRestResult<String> zxConfirmTD(String loanapplyNo, HttpServletRequest request) {
		String[] selectedZx = request.getParameterValues("ids");
		if (selectedZx == null || selectedZx.length == 0) {
			return BaseRestResult.warn("请选中需要的企业征信报告");

		}
		if (selectedZx.length > 1) {
			return BaseRestResult.warn("只能选着一个企业征信报告");
		}
		
		String zxtdId = selectedZx[0];
		O2oEnterpriseZxEntity entity=o2oEnterpriseZxService.getEntityById(zxtdId);
		entity.setLoanapplyNo(loanapplyNo);
		entity.setUpdatezxid(UserHolder.getUser().getNo());
		entity.setUpdatezxname(UserHolder.getUser().getCname());
		entity.setUpdatezxdate(new Date());
		int num=o2oEnterpriseZxService.update(entity);
		if (num>0) {
			BaseRestResult.warn("更新成功");
		}else {
			BaseRestResult.warn("更新失败");
		}
		return HtmlRestResult.buildClosestReloadResult();
	}
	@RequestMapping("/zxdelTD")
	public BaseRestResult<String> zxdelTD(String id) {
		O2oEnterpriseZxEntity entity=o2oEnterpriseZxService.getEntityById(id);
		entity.setLoanapplyNo(null);
		entity.setUpdatezxid(UserHolder.getUser().getNo());
		entity.setUpdatezxname(UserHolder.getUser().getCname());
		entity.setUpdatezxdate(new Date());
		entity.setUpdatezxdate(new Date());
		int num=o2oEnterpriseZxService.update(entity);
		if (num>0) {
			BaseRestResult.warn("删除成功");
		}else {
			BaseRestResult.warn("删除失败");
		}
		return BaseRestResult.info("删除成功").refresh();
	}
	

/**
	 * @Description:
	 * 				<p>
	 *               删除征信
	 *               </p>
	 * @author CXW
	 * @date 2017年9月27日 下午2:39:19
	 * @version V1.0
	 */
	@RequestMapping("/delete")
	public BaseRestResult<String> deleteO2oQYZx(String id) {
		O2oEnterpriseZxEntity entity=o2oEnterpriseZxService.getEntityById(id);
		entity.setIsDel(StatusContexts.O2O_YES);
		int i=o2oEnterpriseZxService.update(entity);
		if (i > 0) {
			return BaseRestResult.info("删除成功！").andRedirect("/enterpriseZx/list");
		}
		return BaseRestResult.warn("删除失败！");
	}
	/**
	 * @Title: tkdetailUploadView
	 * @Description: 征信详情页面查看附件弹出页面
	 * @author 张庆奇
	 * @param id
	 * @param readonly
	 * @return
	 * @return BaseRestResult<String>
	 * @throws
	 * @date 2018年2月6日 上午10:22:42
	 */
	@RequestMapping("/tkdetailUploadView")
	public HtmlRestResult tkdetailUploadView(String id) {
		
		PageResult<Object[]> pageResult = o2oLoanapplyService.findO2oDataListEntityById(id);
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间" };
		OpenButton fileButton=new OpenButton(null, "/file/download?datalistno=");
		fileButton.setShowButtonFilter(new ShowButtonFilter(){

			@Override
			public boolean filter(Object param) {
				Object[] params=(Object[]) param;
				return !"企业征信报告".equals(params[1]);
			}
			
		});
		Button[] detailButton = new Button[] {fileButton};
			
		PaginationInfo datalistInfo = new PaginationInfo(pageResult, titles);
		datalistInfo.setTitleButtons(detailButton);
		datalistInfo.setBuildPagingNavigation(false);
		datalistInfo.setFirstRenderColumnIndex(1);
		datalistInfo.setBuildRowNumber(true);
		ViewContext.put("datalistInfo", datalistInfo);

		return HtmlRestResult.popHtmlFragment("o2ozx/zxfjView");
		
	}

}
